package org.leonos.utils;

import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.DbKit;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 手动控制事务
 * 注意：不可与其他事物控制方法同时使用，如Tx
 * @author LeonXiao
 */
public class Tx4Jfinal {

    /**
     * 开启事务
     */
    public static void beginTran() {
        Connection conn;
        try {
            Config config = DbKit.getConfig();
            if(null != config){
                conn = config.getConnection();
                if(null != conn){
                    config.setThreadLocalConnection(conn);
                    conn.setAutoCommit(false);
                }
            }
        } catch (Exception e) {
            throw (new RuntimeException(e));
        }
    }

    /**
     * 提交事务
     */
    public static void commit() {
        Connection conn = null;
        Config config = null;
        try {
            config = DbKit.getConfig();
            if(null != config){
                conn = config.getThreadLocalConnection();
                if(null != conn){
                    conn.commit();
                }
            }
        } catch (Exception e) {
            throw (new RuntimeException(e));
        } finally{
            closeConn(conn, config);
        }
    }

    /**
     * 事务回滚
     */
    public static void rollback(){
        Connection conn = null;
        Config config = null;
        try {
            config = DbKit.getConfig();
            if(null != config){
                conn = config.getThreadLocalConnection();
                if(null != conn){
                    conn.rollback();
                }
            }
        } catch (Exception e) {
            throw (new RuntimeException(e));
        } finally {
            closeConn(conn, config);
        }
    }

    /**
     * 关闭数据库连接，清除配置
     * @param conn
     *              数据库连接
     * @param config
     *              配置
     */
    private static void closeConn(Connection conn, Config config) {
        try {
            if (null != conn) {
                conn.setAutoCommit(true);
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (null != config) {
                config.removeThreadLocalConnection();
            }
        }
    }
}
